from rest_framework import serializers
from .models import ExperimentStatistics, ExperimentAttachment

class ExperimentAttachmentSerializer(serializers.ModelSerializer):
    """试验附件序列化器"""
    
    class Meta:
        model = ExperimentAttachment
        fields = ['id', 'name', 'size', 'file_type', 'upload_time']
        read_only_fields = ['id', 'upload_time']

class ExperimentStatisticsSerializer(serializers.ModelSerializer):
    """试验统计序列化器"""
    
    attachments = ExperimentAttachmentSerializer(many=True, read_only=True)
    
    # 前端字段映射（驼峰命名转下划线命名）
    experimentType = serializers.CharField(source='experiment_type', max_length=50, required=False, allow_blank=True)
    experimentNumber = serializers.CharField(source='experiment_number', max_length=100, required=False, allow_blank=True)
    experimentName = serializers.CharField(source='experiment_name', max_length=200, required=False, allow_blank=True)
    productType = serializers.CharField(source='product_type', max_length=100, required=False, allow_blank=True)
    testItems = serializers.CharField(source='test_items', max_length=100, required=False, allow_blank=True)
    testEquipment = serializers.CharField(source='test_equipment', max_length=200, required=False, allow_blank=True)
    experimentCommander = serializers.CharField(source='experiment_commander', max_length=100, required=False, allow_blank=True)
    isExternalCollaboration = serializers.CharField(source='is_external_collaboration', max_length=10, required=False, allow_blank=True)
    testCompany = serializers.CharField(source='test_company', max_length=200, required=False, allow_blank=True)
    testContact = serializers.CharField(source='test_contact', max_length=200, required=False, allow_blank=True)
    participantName = serializers.CharField(source='participant_name', max_length=200, required=False, allow_blank=True)
    productQuantity = serializers.CharField(source='product_quantity', max_length=50, required=False, allow_blank=True)
    productNumber = serializers.CharField(source='product_number', max_length=100, required=False, allow_blank=True)
    productEntryDate = serializers.DateField(source='product_entry_date', required=False, allow_null=True)
    testStartDate = serializers.DateField(source='test_start_date', required=False, allow_null=True)
    testEndDate = serializers.DateField(source='test_end_date', required=False, allow_null=True)
    productExitDate = serializers.DateField(source='product_exit_date', required=False, allow_null=True)
    operatingDays = serializers.CharField(source='operating_days', max_length=50, required=False, allow_blank=True)
    reservationApprovalNumber = serializers.CharField(source='reservation_approval_number', max_length=100, required=False, allow_blank=True)
    photoUploaded = serializers.CharField(source='photo_uploaded', max_length=10, required=False, allow_blank=True)
    summaryReport = serializers.CharField(source='summary_report', max_length=200, required=False, allow_blank=True)
    certificateNumber = serializers.CharField(source='certificate_number', max_length=100, required=False, allow_blank=True)
    contractNumber = serializers.CharField(source='contract_number', max_length=100, required=False, allow_blank=True)
    partnerContact = serializers.CharField(source='partner_contact', max_length=200, required=False, allow_blank=True)
    ourContact = serializers.CharField(source='our_contact', max_length=200, required=False, allow_blank=True)
    
    class Meta:
        model = ExperimentStatistics
        fields = [
            'id',
            'experimentType',
            'experimentNumber',
            'experimentName',
            'productType', 
            'testItems',
            'testEquipment',
            'experimentCommander',
            'participants',
            'isExternalCollaboration',
            'testCompany',
            'testContact',
            'participantName',
            'productQuantity',
            'productNumber',
            'productEntryDate',
            'testStartDate',
            'testEndDate',
            'productExitDate',
            'operatingDays',
            'reservationApprovalNumber',
            'photoUploaded',
            'summaryReport',
            'certificateNumber',
            'contractNumber',
            'partnerContact',
            'ourContact',
            'attachments',
            'created_at',
            'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'attachments']
    
    def validate(self, data):
        """数据验证"""
        # 验证日期逻辑，只有当日期字段都不为空时才进行验证
        if ('product_entry_date' in data and data['product_entry_date'] is not None and 
            'test_start_date' in data and data['test_start_date'] is not None):
            if data['product_entry_date'] > data['test_start_date']:
                raise serializers.ValidationError("产品入场日期不能晚于试验开始日期")
        
        if ('test_start_date' in data and data['test_start_date'] is not None and 
            'test_end_date' in data and data['test_end_date'] is not None):
            if data['test_start_date'] > data['test_end_date']:
                raise serializers.ValidationError("试验开始日期不能晚于试验结束日期")
        
        if ('test_end_date' in data and data['test_end_date'] is not None and 
            'product_exit_date' in data and data['product_exit_date'] is not None):
            if data['test_end_date'] > data['product_exit_date']:
                raise serializers.ValidationError("试验结束日期不能晚于产品出场日期")
        
        return data

class ExperimentStatisticsCreateSerializer(serializers.ModelSerializer):
    """试验统计创建序列化器"""
    
    class Meta:
        model = ExperimentStatistics
        fields = [
            'experiment_number',
            'experiment_name', 
            'test_items',
            'test_equipment',
            'experiment_commander',
            'participants',
            'is_external_collaboration',
            'test_company',
            'test_contact',
            'participant_name',
            'product_quantity',
            'product_number',
            'product_entry_date',
            'test_start_date',
            'test_end_date',
            'product_exit_date',
            'operating_days',
            'reservation_approval_number',
            'photo_uploaded',
            'summary_report',
            'certificate_number',
            'contract_number',
            'partner_contact',
            'our_contact'
        ]
    
    def validate(self, data):
        """数据验证"""
        # 验证日期逻辑
        if data.get('product_entry_date') and data.get('test_start_date'):
            if data['product_entry_date'] > data['test_start_date']:
                raise serializers.ValidationError("产品入场日期不能晚于试验开始日期")
        
        if data.get('test_start_date') and data.get('test_end_date'):
            if data['test_start_date'] > data['test_end_date']:
                raise serializers.ValidationError("试验开始日期不能晚于试验结束日期")
        
        if data.get('test_end_date') and data.get('product_exit_date'):
            if data['test_end_date'] > data['product_exit_date']:
                raise serializers.ValidationError("试验结束日期不能晚于产品出场日期")
        
        return data